package com.wenjh.jdmzt.util;

import android.text.Editable;
import android.text.Selection;
import android.text.TextWatcher;
import android.widget.TextView;

public class TooLongValidator implements TextWatcher {
	private final int maxlen;
	private boolean autoInput = true;
	private TextView textView = null;
	private TooLongListener listener = null;
	
	public TooLongValidator(int maxBytesLen, TextView view) {
		this.maxlen = maxBytesLen;
		this.textView = view;
	}
	
	
	public TooLongValidator setTooLongListener(TooLongListener listener) {
		this.listener = listener;
		return this;
	}

	@Override
	public void afterTextChanged(Editable s) {

	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {

	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		String name = s.toString();
		int len = -1;
		try {
			len = name.getBytes("GBK").length ;
		} catch (Exception e) {
		}
		
		
		if(autoInput) {
			
			if(len > maxlen) {
				autoInput = false;
				
				String befStr = name.substring(0, start);
				String afterStr = name.substring(start+count, name.length());
				
				textView.setText(befStr + afterStr);
				Selection.setSelection((Editable)textView.getText(), start);
				
				if(listener != null) {
					listener.onExceeded(textView, s, count);
				}
				
			}
			
		} else {
			autoInput = true;
		}
	}
	
	public interface TooLongListener {
		void onExceeded(TextView textView, CharSequence content, int count);
	}

}
